package com.demo.main.dao;

import com.demo.main.entity.Message;
import com.demo.main.utils.JdbcUtil;

import java.sql.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

public class MessageDao {
    public void addMessage(Message message) throws SQLException {
        String sql = "INSERT INTO messages (username, content, timestamp) VALUES (?, ?, ?)";
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, message.getUsername());
            stmt.setString(2, message.getContent());
            stmt.setTimestamp(3, Timestamp.valueOf(message.getTimestamp()));
            stmt.executeUpdate();
        }
    }

    public List<Message> getAllMessages() throws SQLException, ParseException {
        List<Message> messages = new ArrayList<>();
        String sql = "SELECT * FROM messages ORDER BY timestamp DESC";
        try (Connection conn = JdbcUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String content = rs.getString("content");
                Timestamp timestamp = rs.getTimestamp("timestamp");
                messages.add(new Message(id, username, content, timestamp.toLocalDateTime()));
            }
        }
        return messages;
    }
}
